package com.tkm.expressions.operators

class Complex(var real: Double, var image: Double) {
    override fun toString(): String {
        return "${this.real} + ${this.image}i"
    }
}

//  扩展运算符
operator fun Complex.plus(p: Complex): Complex {
    return Complex(
        this.real + p.real,
        this.image + p.image
    )
}

operator fun Complex.plus(real: Double): Complex {
    return Complex(this.real + real, this.image)
}

operator fun Complex.minus(p: Complex): Complex {
    return Complex(
        this.real - p.real,
        this.image - p.image
    )
}

operator fun Complex.minus(real: Double): Complex {
    return Complex(this.real - real, this.image)
}

operator fun Complex.get(index: Int) = when (index) {
    0 -> this.real
    1 -> this.image
    else -> throw IndexOutOfBoundsException("index: $index")
}

fun main() {
    val complex1 = Complex(1.0, 2.0)
    val complex2 = Complex(2.0, 3.0)
    println(complex1 + complex2)
    println(complex1 - complex2)
    println(complex1 + 1.0)
    println(complex2 - 1.0)
    println(complex1[0])
    println(complex1[1])
}
